package com.my.yc.d0301;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "CookieServlet", value = "/CookieServlet")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取cookie数据
        final Cookie[] cookies = request.getCookies();
        // 没有cookie数据  该数组为空
        final PrintWriter out = response.getWriter();
        if (cookies != null){
            out.print("<ul>");
            for (Cookie cookie : cookies){
                out.printf("<li>%s : %s</li>", cookie.getName(), cookie.getValue());
            }
            out.print("</ul>");
        }
        final String name = request.getParameter("name");
        // 服务器向浏览器发送cookie 数据
        Cookie cookie = new Cookie("name", name);
        // 有效期: 单位: 秒   一周， 有效期0 表示 删除该 cookie
        if (name == null){
            cookie.setMaxAge(0);
        } else {
            cookie.setMaxAge(60 * 60 * 24 *7);
        }
        //  cookie.setPath(); 路径，默认为当前路径
        //  cookie.setDomain(); 域名 => 同源策略

        // 添加到相应对象中
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
